package com.copa.gameStore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.copa.gameStore.client.GameGoodsClient;
import com.copa.gameStore.domain.Cart;
import com.copa.gameStore.domain.GameGoods;
import com.copa.gameStore.dto.CartDto;
import com.copa.gameStore.mapper.CartMapper;
import com.copa.gameStore.service.CartService;
import com.copa.gameStore.vo.CartGoodsVo;
import com.copa.gameStore.vo.CartVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.ValidationException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author copa
 * @createDate 2022-09-27 11:34
 * @function
 */
@Service
public class CartServiceImpl implements CartService {

    @Resource
    private CartMapper cartMapper;

    @Resource
    private GameGoodsClient gameGoodsClient;

    @Override
    public void post(CartDto cartDto) {
        if (!gameGoodsClient.validateGoods(cartDto.getGameGoodsId())) {
            // 校验商品，加入购物车即减库存
            throw new ValidationException("抱歉~该商品不存在~");
        }
        Cart cart = cartMapper.selectOne(new QueryWrapper<Cart>()
                .eq("user_id", cartDto.getUserId())
                .eq("game_goods_id", cartDto.getGameGoodsId()));
        if (Objects.nonNull(cart)) {
            // 如果记录存在，数量累加 这个是因为之前判断库存才这样写
            //cart.setNum(cart.getNum() + cartDto.getNum());
            // 直接修改数量或累加
            cart.setNum(cartDto.getType() == 2 ? cartDto.getNum() : cart.getNum() + cartDto.getNum());
            if (cartMapper.updateById(cart) <= 0) {
                throw new RuntimeException();
            }
            return;
        }
        // 如果是新记录
        cart = new Cart();
        BeanUtils.copyProperties(cartDto, cart);
        if (cartMapper.insert(cart) <= 0) {
            throw new RuntimeException();
        }
    }

    @Override
    public CartVo getCartGoodsVo(Long userId) {
        List<Cart> cartList = cartMapper.selectList(new QueryWrapper<Cart>()
                .eq("user_id", userId));
        List<CartGoodsVo> cartGoodsVoList = new ArrayList<>();
        BigDecimal money = new BigDecimal(0);
        for (Cart cart : cartList) {
            if (!gameGoodsClient.validateGoods(cart.getGameGoodsId())) {
                // 校验商品
                cartMapper.deleteById(cart.getId());
                continue;
            }
            // 正常流程
            GameGoods gameGoods = gameGoodsClient.getById(cart.getGameGoodsId());
            cartGoodsVoList.add(new CartGoodsVo()
                    .setId(cart.getId())
                    .setGameGoods(gameGoods)
                    .setNum(cart.getNum()));
            money = money.add(gameGoods.getPrice().multiply(BigDecimal.valueOf(cart.getNum())));
        }

        return new CartVo().setCartGoodsVo(cartGoodsVoList).setMoney(money);
    }

    @Override
    public void delete(List<Long> ids, Long userId) {
        ids.forEach(id -> {
            Cart cart = Optional.ofNullable(
                    cartMapper.selectOne(new QueryWrapper<Cart>()
                            .eq("user_id", userId).eq("id", id)))
                    .orElseThrow(() -> new ValidationException("非法操作~"));
            GameGoods gameGoods = gameGoodsClient.getById(cart.getGameGoodsId());

            if (cartMapper.delete(new QueryWrapper<Cart>()
                    .eq("id", id)
                    .eq("user_id", userId)) > 0) {
                // 恢复库存
                gameGoodsClient.stock(gameGoods.getId(), -cart.getNum());
            }
        });
    }

    @Override
    public void validateUser(List<Long> cartIds, Long userId) {
        cartIds.forEach(id -> {
            Cart cart = Optional.ofNullable(cartMapper.selectOne(
                            new QueryWrapper<Cart>()
                                    .eq("user_id", userId)
                                    .eq("id", id)))
                    .orElseThrow(() -> new ValidationException("非法操作~"));
            // 改成这里减库存
            gameGoodsClient.stock(cart.getGameGoodsId(), cart.getNum());
        });

    }
}
